package com.cjm.algorithm.tanxin;

public class Ti53 {
    public static void main(String[] args) {
        Ti53 ti53 = new Ti53();
        System.err.println(ti53.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
        System.err.println(ti53.maxSubArray(new int[]{1}));
        System.err.println(ti53.maxSubArray(new int[]{5, 4, -1, 7, 8}));
    }


    public int maxSubArray1(int[] nums) {

        // 这里又是求最大值， 最大
        // dp[i]下标i之前的最大连续子序列和
        // dp[i] = Max{dp[i-1]+nums[i], nums[i]}
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            res = dp[i] > res ? dp[i] : res;
        }
        return res;
    }

    public int maxSubArray(int[] nums) {
        long res = Integer.MIN_VALUE;
        long preMax = Integer.MIN_VALUE;
        for (int num : nums) {
            long curHe = num + preMax;
            long curMax = Math.max(curHe, num);
            res = Math.max(res, curMax);
            preMax = curMax;
        }

        return (int) res;
    }
}
